// mysql -h127.0.0.1 -uroot -p123 -e "select * from edu_iclass_areas" test > /Users/zhengcanrui/WORK/test/test.xls


const fs = require('fs');
const exec = require('child_process').exec;

var createTimestamp = function () {
    return parseInt(new Date().getTime() / 1000) + '';
};

var exportFn = (tableName, dataType, uid) => {
    return new Promise((resolve, reject) => {
        if (dataType == 'excel') {
            var timestamp = createTimestamp();
            var fileName = '/home/export/' + timestamp + '.xls';

            var whereSql = uid ? " where uid=" + uid : "";

            exec('mysql -h127.0.0.1 -uxxf -pxiexiaofei -e "select * from ' + tableName + whereSql + '" production > ' + fileName, (error, stdout, stderr) => {
                if (error) {
                    console.error(`exec error: ${error}`);
                    reject({ code: 0, data: `exec error: ${error}` });
                } else {
                    // fileName
                    console.log('正在读取文件' + fileName)
                    fs.readFile(fileName, (err, data) => {
                        if (err) throw err;
                        console.log('读取成功')
                        resolve({ code: 1, data: data });
                    });
                }
            });

        }
    })
}

module.exports = exportFn;